﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using ShellLib;
using Manina.Windows.Forms;
using PhotonControls;

namespace Photon4
{
    public class MediaFileProcessor
    {
        private string m_strCurrentFile;
        private string m_strCurrentDir;
        private String[] m_strFiles;
        private int m_CurrentIndex;

        public MediaFileProcessor()
        {
            m_strCurrentFile = "";
            m_strCurrentDir = "";
            m_strFiles = null;
            m_CurrentIndex = 0;
        }
        /*  возвращает число файлов, которые надо обработать. 
         */
        private int GetNumFilesToProcess(ImageListView listView)
        {
            if (listView == null)
                return 0;
            int NumFiles = listView.SelectedItems.Count;
            for (int i = 0; i < listView.SelectedItems.Count; i++)
            {
                string strXMLName = System.IO.Path.ChangeExtension(listView.SelectedItems[i].FileName, ".xml");
                if (System.IO.File.Exists(strXMLName))
                    NumFiles++;
            }
            return NumFiles;
        }
        private String[] GetFileNames(ImageListView listView, int NumFiles)
        {
            String[] fileNames = new String[NumFiles];
            for (int i = 0, c = 0; i < listView.SelectedItems.Count; i++)
            {
                fileNames[c++] = listView.SelectedItems[i].FileName;
                string strXMLName = System.IO.Path.ChangeExtension(listView.SelectedItems[i].FileName, ".xml");
                if (System.IO.File.Exists(strXMLName))
                    fileNames[c++] = strXMLName;
            }
            return fileNames;
        }
        private void ScanCurrentDir()
        {
            string[] files = Directory.GetFiles(m_strCurrentDir, "*.*");
            int count = 0;
            for (int i = 0; i < files.Length; i++)
            {
                string ext = System.IO.Path.GetExtension(files[i]).ToLower();
                if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp")
                    count++;
            }
            m_strFiles = null;
            if (count == 0)
                return;
            m_strFiles = new string[count];
            count = 0;
            for (int i = 0; i < files.Length; i++)
            {
                string ext = System.IO.Path.GetExtension(files[i]).ToLower();
                if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp")
                {
                    m_strFiles[count++] = files[i];
                    if (files[i] == m_strCurrentFile)
                        m_CurrentIndex = count - 1;
                }
            }
            if (m_strCurrentFile == "")
                m_CurrentIndex = 0;
            if (m_strFiles.Length > 0)
                m_strCurrentFile = m_strFiles[0];
        }

        /* Удаляет файлы, выбранные в ImageListView 
         */
        public void DeleteFiles(ImageListView listView)
        {
            if (listView == null)
                return;

            ShellLib.ShellFileOperation fo = new ShellFileOperation();
            int NumFiles = GetNumFilesToProcess(listView);


            String[] source = GetFileNames(listView, NumFiles);
            fo.Operation = ShellLib.ShellFileOperation.FileOperations.FO_DELETE;
            fo.OwnerWindow = listView.Handle;
            fo.SourceFiles = source;

            bool RetVal = fo.DoOperation();
            if (!RetVal)
                MessageBox.Show("Delete Complete with errors!");
            m_strCurrentFile = "";
            this.ScanCurrentDir();
        }
        /*   Удаляет текущий файл вмесет с его описанием. 
         */
        public void DeleteFile()
        {
            ShellLib.ShellFileOperation fo = new ShellFileOperation();
            int NumFiles = 1;

            string strXMLFile = System.IO.Path.ChangeExtension(m_strCurrentFile, ".xml");
            if (System.IO.File.Exists(strXMLFile))
                NumFiles = 2;
            String[] source = new String[NumFiles];
            source[0] = this.m_strCurrentFile;
            if (NumFiles == 2)
                source[1] = strXMLFile;
            fo.Operation = ShellLib.ShellFileOperation.FileOperations.FO_DELETE;
            fo.SourceFiles = source;

            bool RetVal = fo.DoOperation();
            if (!RetVal)
                MessageBox.Show("Delete Complete with errors!");
            else
                m_strCurrentFile = "";
            m_strCurrentFile = "";
            this.ScanCurrentDir();
        }
        /*  переименовывает текущий файл. если имеется его описание, то переименовывает и описание
         */
        public void RenameFile()
        {
            FormRename dlg = new FormRename();
            dlg.label2.Text = System.IO.Path.GetFileName(m_strCurrentFile);
            dlg.textBox1.Text = "noname";
            dlg.pictureBox1.Load(m_strCurrentFile);
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string strNewName = System.IO.Path.GetDirectoryName(m_strCurrentFile);
                string extName = System.IO.Path.GetExtension(m_strCurrentFile);
                strNewName += "\\";
                strNewName += dlg.textBox1.Text;

                strNewName = System.IO.Path.ChangeExtension(strNewName, extName);
                System.IO.File.Move(m_strCurrentFile, strNewName);

                string strXMLName = System.IO.Path.ChangeExtension(m_strCurrentFile, ".xml");
                if (System.IO.File.Exists(strXMLName))
                {
                    string strXMLNewName = System.IO.Path.ChangeExtension(strNewName, ".xml");
                    System.IO.File.Move(strXMLName, strXMLNewName);
                }
                m_strCurrentFile = strNewName;
                this.ScanCurrentDir();
            }
            
        }
        /* 
         */
        public void CutFile(string strFileName)
        { 
        
        }
        /* редактирование текстового описания изображения. 
         */
        public void DescribeFile(PhotonControls.FImage image)
        {
            if (m_strCurrentFile == "")
                return;
            string strName = System.IO.Path.ChangeExtension(m_strCurrentFile, ".xml");
            FormDescribe dlg = new FormDescribe();
            dlg.textBox1.Text = image.Description;
            if (dlg.ShowDialog() != DialogResult.OK)
                return ;
            image.Description = dlg.textBox1.Text;
        }
        public void SetCurrentFile(string strFileName)
        {
            if (strFileName == "")
            {
                m_strCurrentDir = "";
                m_strCurrentFile = "";
                return;
            }
            m_strCurrentFile = strFileName;
            string strCurrentDir = System.IO.Path.GetDirectoryName(strFileName);
            if (strCurrentDir != m_strCurrentDir)
            {
                m_strCurrentDir = strCurrentDir;
                ScanCurrentDir();
            }
        }
        public string GetCurrentFile()
        {
            return m_strCurrentFile;
        }
        /* Копирует файлы, выбранные пользователем в ImageListView в 
         * папку, выбранную с испльзованием системной панели ShellBrowseForFolderDialog
         */
        public void CopyToFiles(ImageListView listView)
        {
            ShellLib.ShellBrowseForFolderDialog dlg = new ShellLib.ShellBrowseForFolderDialog();
            if (!dlg.ShowDialog())
                return;

            ShellLib.ShellFileOperation fo = new ShellFileOperation();
            int NumFiles = GetNumFilesToProcess(listView);
            String[] source = GetFileNames(listView, NumFiles);
            String[] dest = new String[NumFiles];
            for (int i = 0; i < NumFiles; i++)
            {
                dest[i] = dlg.FullName + "\\" + System.IO.Path.GetFileName(source[i]);
            }
            fo.Operation = ShellLib.ShellFileOperation.FileOperations.FO_COPY;
            fo.OwnerWindow = listView.Handle;
            fo.SourceFiles = source;
            fo.DestFiles = dest;

            bool RetVal = fo.DoOperation();
            if (!RetVal)
                MessageBox.Show("Copy Complete with errors!");

        }
        public void CopyToFile()
        {
            ShellLib.ShellBrowseForFolderDialog dlg = new ShellLib.ShellBrowseForFolderDialog();
            if (!dlg.ShowDialog())
                return;
            
            ShellLib.ShellFileOperation fo = new ShellFileOperation();
            int NumFiles = 1;

            string strXMLFile = System.IO.Path.ChangeExtension(m_strCurrentFile, ".xml");
            if (System.IO.File.Exists(strXMLFile))
                NumFiles = 2;
            String[] source = new String[NumFiles];
            source[0] = this.m_strCurrentFile;
            if (NumFiles == 2)
                source[1] = strXMLFile;
            String[] dest = new String[NumFiles];
            for (int i = 0; i < NumFiles; i++)
            {
                dest[i] = dlg.FullName + "\\" + System.IO.Path.GetFileName(source[i]);
            }
            fo.Operation = ShellLib.ShellFileOperation.FileOperations.FO_COPY;
            fo.SourceFiles = source;
            fo.DestFiles = dest;
            bool RetVal = fo.DoOperation();
            if (!RetVal)
                MessageBox.Show("Copy Complete with errors!");
        }
        /* Перемещает файлы, выбранные пользователем в ImageListView в 
         * папку, выбранную с испльзованием системной панели ShellBrowseForFolderDialog
         */
        public void MoveToFiles(ImageListView listView)
        {
            ShellLib.ShellBrowseForFolderDialog dlg = new ShellLib.ShellBrowseForFolderDialog();
            if (!dlg.ShowDialog())
                return;

            ShellLib.ShellFileOperation fo = new ShellFileOperation();
            int NumFiles = GetNumFilesToProcess(listView);
            String[] source = GetFileNames(listView, NumFiles);
            String[] dest = new String[NumFiles];
            for (int i = 0; i < NumFiles; i++)
            {
                dest[i] = dlg.FullName + "\\" + System.IO.Path.GetFileName(source[i]);
            }
            fo.Operation = ShellLib.ShellFileOperation.FileOperations.FO_MOVE;
            fo.OwnerWindow = listView.Handle;
            fo.SourceFiles = source;
            fo.DestFiles = dest;

            bool RetVal = fo.DoOperation();
            if (!RetVal)
                MessageBox.Show("Move Complete with errors!");
            m_strCurrentFile = "";
            this.ScanCurrentDir();
        }
        /* Перемещает текущий файл в папку заданную пользователем с использванием
         * системной панели ShellBrowseForFolderDialog
         */
        public void MoveToFile()
        {
            ShellLib.ShellBrowseForFolderDialog dlg = new ShellLib.ShellBrowseForFolderDialog();
            if (!dlg.ShowDialog())
                return;

            ShellLib.ShellFileOperation fo = new ShellFileOperation();
            int NumFiles = 1;

            string strXMLFile = System.IO.Path.ChangeExtension(m_strCurrentFile, ".xml");
            if (System.IO.File.Exists(strXMLFile))
                NumFiles = 2;
            String[] source = new String[NumFiles];
            source[0] = this.m_strCurrentFile;
            if (NumFiles == 2)
                source[1] = strXMLFile;
            String[] dest = new String[NumFiles];
            for (int i = 0; i < NumFiles; i++)
            {
                dest[i] = dlg.FullName + "\\" + System.IO.Path.GetFileName(source[i]);
            }
            fo.Operation = ShellLib.ShellFileOperation.FileOperations.FO_MOVE;
            fo.SourceFiles = source;
            fo.DestFiles = dest;
            bool RetVal = fo.DoOperation();
            if (!RetVal)
                MessageBox.Show("Copy Complete with errors!");
            m_strCurrentFile = "";
            this.ScanCurrentDir();
        }

        public string GetNextFile()
        {
            if (m_strFiles == null || m_strFiles.Length == 0)
                return null;
            m_CurrentIndex++;
            if (m_CurrentIndex >= m_strFiles.Length)
            {
                m_CurrentIndex = m_strFiles.Length - 1;
            }
            m_strCurrentFile = m_strFiles[m_CurrentIndex];
            return m_strCurrentFile;   
        }
        public string GetPrevFile()
        {
            if (m_strFiles == null || m_strFiles.Length == 0)
                return null;
            m_CurrentIndex --;
            if (m_CurrentIndex < 0)
            {
                m_CurrentIndex = 0;
            }
            m_strCurrentFile = m_strFiles[m_CurrentIndex];
            return m_strCurrentFile;           
        }
        public int FileCount()
        {
            if (m_strFiles != null)
                return m_strFiles.Length;
            return 0;
        }
        public int CurrentIndex()
        {
            return m_CurrentIndex;
        }
    }
}
